package com.example.lucky.draw.server.service.impl;

import com.example.lucky.draw.server.common.enums.DrawEnum;
import com.example.lucky.draw.server.common.handler.DrawException;
import com.example.lucky.draw.server.protocol.po.ActivityRule;
import com.example.lucky.draw.server.protocol.po.Rule;
import com.example.lucky.draw.server.repository.ActivityRuleRepository;
import com.example.lucky.draw.server.repository.RuleRepository;
import com.example.lucky.draw.server.service.IActivityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityRuleServiceImpl implements IActivityRuleService {

    @Autowired
    private ActivityRuleRepository activityRuleRepository;

    @Autowired
    private RuleRepository ruleRepository;

    @Override
    public List<Rule> findRuleByActivityId(Long id) {
        List<ActivityRule> activityRules = activityRuleRepository.findByActivityId(id);
        List<Long> ids = activityRules.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        return ruleRepository.findAllById(ids);
    }

    @Override
    public List<Rule> noBindRule(Long id) {
        List<ActivityRule> activityRules = activityRuleRepository.findByActivityId(id);
        List<Long> excludedIds = activityRules.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        Integer status=Integer.valueOf(DrawEnum.ENABLE.getCode());

        if (excludedIds.isEmpty()){
            return ruleRepository.findByStatusEquals(status);
        }
        return ruleRepository.findByIdNotInAndStatusEquals(excludedIds,status);
    }

    @Override
    public void saveAll(List<ActivityRule> activityRules) {
        List<ActivityRule> activityRuleList = activityRuleRepository.saveAll(activityRules);
        if (activityRuleList.isEmpty()){
            throw new DrawException(DrawEnum.INSERT_ERROR);
        }
    }
}
